import { Modal } from '@douyinfe/semi-ui';
import DictionaryDetail from './dictionary-detail';
import DictionaryEdit from './dictionary-edit';
import { useEffect, useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';
import { usePageContext, useStoreContext } from '../dictionary-context';
import { createItem, fetchItems, updateItem } from '../reducer/dictionary-actions';

const DictionaryEntityDialog = ({ open, onClose, editable = false }: any) => {
  const { id } = useParams();
  const PageContext = usePageContext();
  const [title, setTitle] = useState('');

  const PageAction = useMemo(() => {
    return {
      queryParams: PageContext.queryParams,
    };
  }, [PageContext]);

  const {
    state:  {dictionary},
    useDispatch,
  } = useStoreContext();

  const { entities, actionsLoading,key} = dictionary;


  // Title couting
  useEffect(() => {
    let _title = id ? '' : '新建';
    if (id) {
      _title = `编辑`;
    }

    setTitle(_title);
    // eslint-disable-next-line
  }, [id, actionsLoading]);


  const entityForEdit = useMemo(() => {
    if (id) {
      
      const _entity = {...entities?.filter((rule: any) => rule.id.toString() === id.toString())[0]};

      return _entity;
    }
    return null;
  }, [entities, id]);

  const persistEntity = (entity: any) => {
    if (!id) {
      //@ts-ignore
      useDispatch(createItem, entity).then((success) => {
        if(success){
          onClose();
          useDispatch(fetchItems, PageAction.queryParams);
        }
       
      });
    } else {
      //@ts-ignore
      useDispatch(updateItem, entity).then((success) => {
        if(success){
          onClose();
          useDispatch(fetchItems, PageAction.queryParams);
        }
       
      });
    }
  };

  return (
    <Modal
      title={title}
      size="medium"
      visible={open}
      // onOk={handleOk}
      footer={null}
      onCancel={onClose}
    >
      {editable ? (
        <>
          <DictionaryEdit entity={entityForEdit} persistEntity={persistEntity} />
        </>
      ) : (
        <DictionaryDetail entity={entityForEdit} />
      )}
    </Modal>
  );
};

export default DictionaryEntityDialog;
